<?php
declare (strict_types=1);

namespace app\model;


/**
 * Class AgentSalesman
 *
 * @property int $id 自增id
 * @property int $agent_id 代理商ID
 * @property int $salesman_id 业务员ID
 * @property int $serv_type 业务类型名，取值来自代码 constant->PRODUCT_SERV_TYPE
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property int $is_deleted 是否删除 0 否 1是
 * @property-read \app\model\Salesman $salesman
 * @property-read \app\model\Agent $agent
 * @property-read string $serv_type_format
 */
class AgentSalesman extends CommonModel
{
    // 隐藏字段
    protected $hidden = ['created_at', 'updated_at'];

    /**
     * 业务员
     * @return \think\model\relation\HasOne
     */
    public function salesman()
    {
        return $this->hasOne(Salesman::class, 'id', 'salesman_id');
    }

    /**
     * 代理商
     * @return \think\model\relation\HasOne
     */
    public function agent()
    {
        return $this->hasOne(Agent::class, 'id', 'agent_id');
    }

    /**
     * serv_type 产品类型映射
     * @param $value
     * @param $model
     * @return string
     */
    public function getServTypeFormatAttr($value, $model)
    {
        return @PRODUCT_SERV_TYPE[$model['serv_type']]['name'] ?? '';
//        return SERVICE_TYPE[$model['serv_type']] ?? '';
    }

    /**
     * 获取业务员ID  根据代理商ID和产品
     * @param $agentId 代理商ID
     * @param $servtype 产品类型
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSalesmanIdByAgentId($agentId, $servtype)
    {
        $model = self::where([
            'agent_id' => $agentId,
            'serv_type' => $servtype,
            'is_deleted' => DELETE_TYPE_NO
        ])
            ->order('id desc')
            ->find();
        $salesmanId = $model->salesman_id ?? 0;
        // 查看该业务员是否被禁用 或删除
        if ($salesmanId) {
            $exit = Salesman::where([
                'id' => $salesmanId,
                'is_deleted' => DELETE_TYPE_NO,
                'status' => Salesman::C_STATUS_OPEN
            ])->findOrEmpty();
            if ($exit->isEmpty()) {
                $salesmanId = 0;
            }
        }
        return $salesmanId;
    }

    /**
     * 业务员代理商数量统计
     * @param $salesmanId
     * @return mixed
     */
    public static function agentSalesmanNum($salesmanId)
    {
        $count = AgentSalesman::where(['salesman_id' => $salesmanId, 'is_deleted' => DELETE_TYPE_NO])
            ->group('agent_id')
            ->field('id')
            ->count();
        return $count;
    }
}